#include "base/log.h"
#include "base/thread.h"

#include "base/threadpool.h"
namespace net_tools::base{
Threadpool::Threadpool(int pool_size,int task_queue_max_size)
  :task_queue_(),
   thread_vector_(),
   thread_pool_size_(pool_size),
   task_queue_max_size_(task_queue_max_size),
   mutex_(),
   cond_(mutex_)
{
  Log::Init();
  if(thread_pool_size_ < 1){
    NT_LOG_WARN << "pool_size小于1 为:" << thread_pool_size_ << NT_LOG_ENDL;
    thread_pool_size_ = 0;
  }
  NT_LOG_INFO << "thread pool thread size:" << thread_pool_size_ << NT_LOG_ENDL;
  for(size_t count = 0;count < thread_pool_size_;++count){
    std::string thread_name = "Work_thread_" + std::to_string(count);
    Thread* thread = new Thread([this]{Thread_todo();},thread_name);
    thread->Start();
    thread_vector_.push_back(thread);
  }
};

Threadpool::~Threadpool(){
  NT_LOG_ERROR << "threadpool been ~" << NT_LOG_ENDL;
};

void Threadpool::Addtask(func task){
  mutex_.Lock();
  if(task_queue_.size() >= task_queue_max_size_){
    mutex_.Unlock();
    task();
    return;
  }
  task_queue_.push(std::move(task));
  cond_.Signal_one();
  mutex_.Unlock();
};
void Threadpool::Thread_todo(){
  while(true){
    func func_;
    NT_LOG_TRACE << "Thread work" << NT_LOG_ENDL;
    mutex_.Lock();
    if(task_queue_.empty()) [[unlikely]]{
      cond_.Wait();
    }
    func_ = std::move(task_queue_.front());
    task_queue_.pop();
    mutex_.Unlock();
    func_();
  }
};

} // namespace net_tools::base